<template>
  <div class="container">
    <div class="app-container">
      <div class="left">
        <el-input
          v-model.trim="queryParams.keyword"
          style="margin-bottom:10px"
          type="text"
          prefix-icon="el-icon-search"
          size="small"
          placeholder="输入员工姓名全员搜索"
          @input="handleInput"
        />
        <!-- 树形组件 -->
        <el-tree
          ref="deptTree"
          node-key="id"
          :data="depts"
          :props="defaultProps"
          :expand-on-click-node="false"
          default-expand-all
          highlight-current
          @current-change="selectNode"
        />
      </div>
      <div class="right">
        <el-row class="opeate-tools" type="flex" justify="end">
          <el-button v-permission="'add-employee'" size="mini" type="primary" @click="$router.push('/employee/detail')">添加员工</el-button>
          <el-button size="mini" @click="click">excel导入</el-button>
          <el-button size="mini" @click="exportExcelClick">excel导出</el-button>
        </el-row>
        <!-- 表格组件 -->
        <el-table :data="employeeList">
          <el-table-column prop="staffPhoto" label="头像" width="80px" align="center">
            <template #default="{row}">
              <el-avatar v-if="row.staffPhoto" :size="30" :src="row.staffPhoto" />
              <span v-else class="username">{{ row.username?.charAt(0) }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="username" label="姓名" />
          <el-table-column prop="mobile" label="手机号" sortable />
          <el-table-column prop="workNumber" label="工号" sortable />
          <el-table-column prop="formOfEmployment" label="聘用形式">
            <template #default="{row}">
              <span v-if="row.formOfEmployment === 1">正式</span>
              <span v-else-if="row.formOfEmployment === 2">非正式</span>
              <span v-else>其它</span>
            </template>
          </el-table-column>
          <el-table-column prop="departmentName" label="部门" />
          <el-table-column prop="timeOfEntry" label="入职时间" sortable />
          <el-table-column label="操作">
            <template #default="{row}">
              <el-button type="text" size="mini" @click="$router.push(`/employee/detail/${row.id}`)">查看</el-button>
              <el-button type="text" size="mini" @click="roleBtnClick(row)">角色</el-button>
              <el-popconfirm
                title="您确定删除吗？"
                @onConfirm="delConfirmClick(row)"
              >
                <el-button slot="reference" v-permission="'del-employee'" type="text" size="mini">删除</el-button>
              </el-popconfirm>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页 -->
        <el-row type="flex" justify="end" style="height: 60px" align="middle">
          <el-pagination
            layout="total, prev, pager, next"
            :total="queryParams.total"
            :current-page="queryParams.page"
            :page-size="queryParams.pagesize"
            @current-change="handleCurrentChange"
          />

        </el-row>
      </div>
    </div>
    <import-excel
      :show-excel-dialog.sync="showExcelDialog"
      @uploadExcelSuccess="getEmployeeList"
    />
    <!-- 员工分配角色的弹层 -->
    <el-dialog title="分配角色" :visible.sync="showRoleDialog" @close="close">
      <el-checkbox-group v-model="roleIds">
        <el-checkbox v-for="item in roleList" :key="item.id" :label="item.id">
          {{ item.name }}
        </el-checkbox>
      </el-checkbox-group>

      <template #footer>
        <el-row type="flex" justify="center">
          <el-button type="primary" size="mini" @click="assignRoleConfirmClick">确定</el-button>
          <el-button size="mini" @click="close">取消</el-button>
        </el-row>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { getEmployeesAPI, exportExcelAPI, deleteEmployeeAPI, getEnableRolesAPI, getEmployeeDetailAPI, assignRoleAPI } from '@/api/employee'
import { getDeptmentsAPI } from '@/api/department'
import { tranListToTreeDate } from '@/utils'
import FileSaveAs from 'file-saver'
import ImportExcel from './components/import-excel.vue'
export default {
  name: 'Employee',
  components: {
    ImportExcel
  },
  data() {
    return {
      depts: [],
      defaultProps: {
        children: 'children',
        label: 'name'
      },
      queryParams: {
        departmentId: null,
        total: 0,
        page: 1,
        pagesize: 10,
        keyword: ''
      },
      employeeList: [],
      showExcelDialog: false,
      showRoleDialog: false,
      // 已启用的角色列表
      roleList: [],
      roleIds: [],
      currentId: null
    }
  },
  created() {
    this.getDepartmentList()
  },
  methods: {
    pointsBindBtn(points) {
      return this.$store.state.user.userInfo.roles.points.includes(`${points}`)
    },
    async assignRoleConfirmClick() {
      await assignRoleAPI({
        id: this.currentId,
        roleIds: this.roleIds
      })
      this.$message.success('分配角色成功')
      this.close()
    },
    close() {
      this.showRoleDialog = false
      this.roleIds = []
    },
    async roleBtnClick(row) {
      this.currentId = row.id
      this.showRoleDialog = true
      this.roleList = await getEnableRolesAPI()
      const { roleIds } = await getEmployeeDetailAPI(row.id)
      this.roleIds = roleIds
    },
    async delConfirmClick(row) {
      await deleteEmployeeAPI(row.id)
      this.$message.success('删除角色成功')
      if (this.queryParams.page > 1 && this.employeeList.length === 1) {
        this.queryParams.page--
      }
      this.getEmployeeList()
    },
    click() {
      this.showExcelDialog = true
    },
    async exportExcelClick() {
      const result = await exportExcelAPI()
      FileSaveAs(result, '员工列表.xlsx')
    },
    handleInput() {
      clearTimeout(this.timer)
      this.timer = setTimeout(() => {
        this.queryParams.page = 1
        this.getEmployeeList()
      }, 300)
    },
    handleCurrentChange(currentPage) {
      this.queryParams.page = currentPage
      this.getEmployeeList()
    },
    async getEmployeeList() {
      const { rows, total } = await getEmployeesAPI(this.queryParams)
      this.employeeList = rows
      this.queryParams.total = total
    },
    // 组织架构树形节点被点击事件：点击哪一个部门就记录那个部门的id
    selectNode(nodeDate) {
      this.queryParams.page = 1
      this.queryParams.departmentId = nodeDate.id
      this.getEmployeeList()
    },
    // 调用组织架构部门列表接口方法
    async getDepartmentList() {
      this.depts = tranListToTreeDate(await getDeptmentsAPI())
      this.queryParams.departmentId = this.depts[0].id
      this.$nextTick(() => {
        this.$refs.deptTree.setCurrentKey(this.depts[0].id)
      })
      this.getEmployeeList()
    }
  }
}
</script>

<style lang="scss" scoped>
.app-container {
  background: #fff;
  display: flex;
  .left {
    width: 280px;
    padding: 20px;
    border-right: 1px solid #eaeef4;
  }
  .right {
    flex: 1;
    padding: 20px;
    .opeate-tools {
      margin:10px ;
    }
    .username {
      height: 30px;
      width: 30px;
      line-height: 30px;
      text-align: center;
      border-radius: 50%;
      color: #fff;
      background: #04C9BE;
      font-size: 12px;
      display:inline-block;
    }
  }
}

</style>
